import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Jiange
 * @create 2021-05-13-14:05
 */

/**
 * 在信号量上定义两种操作：
 *      acquire：当一个线程调用这个操作时，他要么通过成功获取信号量（信号量减一） 要不一直等下去 等到其他线程释放
 *      relase  释放信号量值 加一  然后唤醒等待的进程
 */
public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(3);
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"\t"+ "藏用车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"\t"+ "离开车位");
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println("最后执行-------------");
    }
}
